import { watch } from 'vue'
import i18n from '@/i18n'
import { DEFAULT_LANG } from '@/constants'
import { getItem } from '@/utils/lib/storage'
import { useAppStore } from '@/store'
import { HttpCode, Lang } from '@/enums'
import { bus } from '@/utils'
import router from '@/router'
export const getLangList = () => [
	{
		id: Lang.en,
		text: 'English',
		img: 'lang/en'
	},
	{
		id: Lang.zh,
		text: '中文简体',
		img: 'lang/zh'
	},
	{
		id: Lang.zhTW,
		text: '中文繁体',
		img: 'lang/zh'
	}
]

export const getLang = (): Lang => {
	let lang = getItem('app')?.lang
	// if (!lang) {
	// 	const sysLang = (navigator.language || '').toLocaleLowerCase().split('-')[0]
	// 	if (LangList.includes(sysLang as Lang)) {
	// 		lang = sysLang
	// 	}
	// }
	if (!lang) {
		lang = DEFAULT_LANG
	}
	return lang
}

export const changeLang = (lang: any) => {
	i18n.global.locale.value = lang
	const currentRouteLocale = router.currentRoute.value.params.locale as string
	if (currentRouteLocale) {
		const newPath = router.currentRoute.value.path.replace(currentRouteLocale, lang)
		router.push(newPath)
	}
	bus.$emit('LANG_EVENT', lang)
	window.document.documentElement.setAttribute('lang', lang)
}

export const useLang = () => {
	const appStore = useAppStore()
	watch(
		() => appStore.lang,
		(val) => {
			changeLang(val)
		},
		{
			immediate: true
		}
	)
}

/**
 * 国际化快捷函数
 * @param  {...any} params
 * @param  {...any} key
 * @returns
 */
export function t(key: string | undefined, param: any = {}) {
	return key ? i18n.global.t(key, param) : ''
}

export function tError(data: any) {
	if (typeof data === 'object') {
		const { code, msg } = data
		if (code in HttpCode) {
			// TODO 某些提示语需要传入参数,可在这里新建条件分支; 比如密码错误次数,验证码倒计时; [131,132,333];
			return t(`httpCode.${code}`, { code, msg })
		} else {
			// return `${t(`httpCode.${HttpCode.Unknown}`)}\n[${code || ''}]\n${msg || ''}`
			return `${msg}`
		}
	} else if (typeof data === 'string') {
		return t(data)
	} else {
		return t(`httpCode.${HttpCode.Unknown}`)
	}
}

/**
 * 国际化请选择
 * @param  {...any} keys
 * @returns
 */
export function tSelect(...keys: any[]) {
	keys = keys.map((key) => t(key))
	return t('tip.select', keys)
}

/**
 * 国际化请输入
 * @param  {...any} keys
 * @returns
 */
export function tInput(...keys: any[]) {
	// keys = keys.map((key) => t(key))
	keys = keys.map((key) => String(t(key)).toLowerCase())
	return t('tip.input', keys)
}

/**
 * 国际化标签
 * @param {*} key
 * @returns
 */
export function tLabel(key: string) {
	return t('tip.label', [t(key)])
}

export function tName(data: any) {
	let res = ''
	if (data) {
		const appStore = useAppStore()
		res = data[appStore.lang]
	}
	return res
}
